package bo.gustavo.scrapper.ui;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.Properties;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;

import org.apache.commons.lang.StringUtils;

import bo.gustavo.scrapper.Scrapper;
import bo.gustavo.scrapper.export.CSVExporter;
import bo.gustavo.scrapper.export.JSONConverter;
import bo.gustavo.scrapper.util.PropertiesKeys;
import bo.gustavo.scrapper.zip.Unzipper;

public class MainWindow extends JFrame {

	private JPanel contentPane;

	private Scrapper scrapper;

	private JLabel lblScrapperApps = new JLabel("Number of apps scrapped: ");

	private JTextField txtPages;

	private Properties prop;

	private int pagesToScrap;

	private JButton btnSet = new JButton("Set Value");

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (ClassNotFoundException e1) {
		} catch (InstantiationException e1) {
		} catch (IllegalAccessException e1) {
		} catch (UnsupportedLookAndFeelException e1) {
		}

		EventQueue.invokeLater(new Runnable() {

			public void run() {
				try {
					MainWindow frame = new MainWindow();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public MainWindow() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 199, 216);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);

		JPanel panel = new JPanel();
		contentPane.add(panel, BorderLayout.NORTH);
		panel.setLayout(new GridLayout(0, 1, 0, 0));

		JPanel panel_5 = new JPanel();
		panel.add(panel_5);

		JLabel lblGooglePlayScrapper = new JLabel("Google Play Scrapper");
		panel_5.add(lblGooglePlayScrapper);
		lblGooglePlayScrapper.setFont(new Font("Tahoma", Font.BOLD, 15));

		JPanel panel_4 = new JPanel();
		panel.add(panel_4);

		JLabel lblNumberOfPages = new JLabel("Number of pages to scrap: ");
		panel_4.add(lblNumberOfPages);

		txtPages = new JTextField();
		panel_4.add(txtPages);
		txtPages.setColumns(10);

		btnSet.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent arg0) {
				asignPagesToScrapValue();
			}

		});
		panel_4.add(btnSet);

		JPanel panel_1 = new JPanel();
		contentPane.add(panel_1, BorderLayout.WEST);
		panel_1.setLayout(new GridLayout(0, 1, 0, 0));

		JButton btnStartScrapping = new JButton("Start scrapping");
		btnStartScrapping.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				startWork();
			}
		});
		panel_1.add(btnStartScrapping);

		JButton btnStopScrapping = new JButton("Stop Scrapping");
		btnStopScrapping.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				stopWork();
			}
		});
		panel_1.add(btnStopScrapping);

		JPanel panel_2 = new JPanel();
		contentPane.add(panel_2, BorderLayout.SOUTH);

		panel_2.add(lblScrapperApps);

		JPanel panel_3 = new JPanel();
		panel_3.setBorder(new EmptyBorder(0, 150, 0, 0));
		contentPane.add(panel_3, BorderLayout.EAST);

		JButton btnCSV = new JButton("Export to CSV");
		btnCSV.addActionListener(new SaveL());
		panel_3.setLayout(new GridLayout(0, 1, 0, 0));
		panel_3.add(btnCSV);

		JButton btnHTML = new JButton("Export to HTML");
		btnHTML.addActionListener(new SaveDirectory());
		panel_3.add(btnHTML);
		this.pack();
		try {
			prop = new Properties();
			prop.load(this.getClass().getResourceAsStream("/scrapper.properties"));
			System.out.println(prop.toString());
		} catch (IOException e) {
			System.out.println("file not found");
			e.printStackTrace();
		}
		pagesToScrap = Integer.valueOf(prop.getProperty(PropertiesKeys.PAGES_TO_SCRAP));
		scrapper = new Scrapper(this, prop, pagesToScrap);
		txtPages.setText(String.valueOf(pagesToScrap));

	}

	public void setNumberAppsScrapper(int amount) {
		lblScrapperApps.setText("Number of apps scrapped: " + amount);
		this.repaint();
	}

	private void startWork() {
		scrapper.startSearch();
		btnSet.setEnabled(false);

	}

	private void stopWork() {
		scrapper.stopSearch();
		btnSet.setEnabled(true);
	}

	private void asignPagesToScrapValue() {
		try {
			scrapper.setPagesToScrap(Integer.valueOf(txtPages.getText()));
		} catch (NumberFormatException e) {
		}
	}

	class SaveL implements ActionListener {

		public void actionPerformed(ActionEvent e) {
			JFileChooser fc = new JFileChooser();
			fc.setFileFilter(new FileNameExtensionFilter("CSV (*.csv)", "csv"));
			int rVal = fc.showSaveDialog(MainWindow.this);
			if (rVal == JFileChooser.APPROVE_OPTION) {
				String fileName = fc.getSelectedFile().getPath();
				if (!StringUtils.endsWith(fileName, ".csv")) {
					fileName = fileName + ".csv";
				}
				CSVExporter.exportToCSV(fileName);
			}

		}
	}

	class SaveDirectory implements ActionListener {

		public void actionPerformed(ActionEvent e) {
			JFileChooser fc = new JFileChooser();
			fc.setDialogTitle("Select a directory");
			fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
			int rVal = fc.showSaveDialog(MainWindow.this);
			if (rVal == JFileChooser.APPROVE_OPTION) {
				String path = fc.getSelectedFile().getPath();
				Unzipper.Unzip(path);
				JSONConverter.convertToJSON(path + File.separator + "Results" + File.separator + "sources" + File.separator + "data.json");
			}
		}
	}
}
